<?php

namespace App\Http\Controllers\Note;

use App\Http\Controllers\Controller;
use App\Models\Note\Doc;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class DocController extends Controller
{
    public function index(Request $request)
    {
        $query = new Doc();
        if ($request->input('keyword')) {
            $query = $query->where('title', 'like', '%' . $request->input('keyword') . '%');
        }
        $obj = $query->orderBy('updated_at', 'desc')->paginate($request->input('page_size', 25));
        return $this->response($obj);
    }

    public function view($id)
    {
        $obj = Doc::find($id);
        return $this->response($obj);
    }

    public function store(Request $request, Doc $obj)
    {
        $all = $request->all();
        $obj->fill($all);
        $obj->save();
        return $this->response($obj->id);
    }


    public function update($id, Request $request)
    {
        $obj = Doc::where('id', $id)->first();
        $obj->update($request->all());
        return $this->response($obj->id);
    }

    public function storage($id, Request $request)
    {
        $obj = Doc::where('id', $id)->first();
        $path = 'doc/' . date("Ymd") . '/' . $id . '.md';
        Storage::disk('public')->put($path, $request->input('content'));
        $obj->url = Storage::disk('public')->url($path);
        $obj->save();
        return $this->response($obj->id);
    }

    public function destroy($id)
    {
        $obj = Doc::find($id);
        Storage::disk('public')->delete(str_replace('/doc/', "", $obj->url));
        $obj->delete();
        return $this->response($obj->id);
    }
}
